package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.MergeVo;
import com.atguigu.gulimall.ware.vo.PurchaseDoneVo;
import com.atguigu.gulimall.ware.vo.PurchaseItemVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotEmpty;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils getUnreceiveList() {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        // 获取新建和已分配的
        wrapper.eq("status", WareConstant.PurchaseStatusEnum.CREATED.getCode())
                .or().eq("status", WareConstant.PurchaseStatusEnum.ASSIGNED.getCode());
        Map<String, Object> map = new HashMap<>();
        map.put("page", "1");
        map.put("limit", "1000");
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(map),
                wrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void merge(MergeVo mergeVo) {
        // 判断purchaseId是否为空, 空为创建新单子, 非空为加入单子
        Long purchaseId = mergeVo.getPurchaseId();
        @NotEmpty List<Long> items = mergeVo.getItems();
        if (purchaseId == null) {
            // 新建单子
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        // 确定采购单是新建和已分配才可以合并
        PurchaseEntity purchaseEntity = this.getById(purchaseId);
        if (purchaseEntity != null &&
                (purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                        purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())) {
            // 修改detail的purchase_id
            Long finalPurchaseId = purchaseId;
            List<PurchaseDetailEntity> purchaseDetailEntities = items.stream().map(item -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(item);
                purchaseDetailEntity.setPurchaseId(finalPurchaseId);
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(purchaseDetailEntities);
        }
    }

    @Transactional
    @Override
    public void received(List<Long> items) {
        // 获取采购单子,确认状态
        List<PurchaseEntity> purchaseEntities = (List<PurchaseEntity>) this.listByIds(items);
        List<PurchaseEntity> purchaseEntityList = purchaseEntities.stream().filter(item -> {
            return item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                    item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode();
        }).collect(Collectors.toList());

        List<PurchaseDetailEntity> purchaseDetailIds = new ArrayList<>();
        // 修改采购单子状态
        for (PurchaseEntity purchaseEntity : purchaseEntityList) {
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVED.getCode());
            // 收集采购需求
            List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService
                    .list(new QueryWrapper<PurchaseDetailEntity>()
                            .eq("purchase_id", purchaseEntity.getId()));
            for (PurchaseDetailEntity purchaseDetailEntity : purchaseDetailEntities) {
                purchaseDetailEntity.setStatus(WareConstant
                        .PurchaseDetailStatusEnum.BUYING.getCode());
            }
            purchaseDetailIds.addAll(purchaseDetailEntities);
        }
        this.updateBatchById(purchaseEntityList);
        // 修改采购需求状态
        purchaseDetailService.updateBatchById(purchaseDetailIds);

    }

    @Transactional
    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) {
        Long id = purchaseDoneVo.getId();
        List<PurchaseItemVo> purchaseItemVoList = purchaseDoneVo.getItems();

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        AtomicBoolean flag = new AtomicBoolean(true);
        // 修改采购需求状态
        List<PurchaseDetailEntity> purchaseDetailEntities = purchaseItemVoList.stream().map(item -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item.getItemId());
            Integer status = item.getStatus();
            if (status == WareConstant.PurchaseDetailStatusEnum.HAS_ERROR.getCode()) {
                flag.set(false);
            }
            purchaseDetailEntity.setStatus(item.getStatus());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(purchaseDetailEntities);

        // 修改采购单状态 (根据采购需求完成状态修改)
        purchaseEntity.setStatus(flag.get() ? WareConstant.PurchaseStatusEnum.FINISHED.getCode() :
                WareConstant.PurchaseStatusEnum.HAS_ERROR.getCode());
        this.updateById(purchaseEntity);

        // 修改商品库存
        for (PurchaseItemVo purchaseItemVo : purchaseItemVoList) {
            if (purchaseItemVo.getStatus() == WareConstant.PurchaseDetailStatusEnum.FINISHED.getCode()) {
                Long itemId = purchaseItemVo.getItemId();
                PurchaseDetailEntity purchaseDetailEntity = purchaseDetailService.getById(itemId);
                if (purchaseDetailEntity != null) {
                    Long skuId = purchaseDetailEntity.getSkuId();
                    Integer skuNum = purchaseDetailEntity.getSkuNum();
                    Long wareId = purchaseDetailEntity.getWareId();
                    wareSkuService.addStock(skuId, skuNum, wareId);
                }
            }
        }
    }

}